package cn.tedu.travelsystem.base.utils;

import cn.tedu.travelsystem.base.exception.AccessLimitException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AccessLimitUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 检查 IP 地址是否频繁访问
    public boolean isFrequent(String key, int maxRequests, int timeWindowInSeconds) {
        // 计数器：检查在指定时间窗口内的请求次数
        Long count = redisTemplate.opsForValue().increment(key, 1);
        if (count == 1) {
            redisTemplate.expire(key, timeWindowInSeconds, TimeUnit.SECONDS); // 设置过期时间
        }
        return count != null && count > maxRequests; // 如果超过最大请求次数，返回 true
    }
    public void checkAccessFrequency(String key, int maxRequests, int seconds) {
        if (isFrequent(key, maxRequests, seconds)) {
            throw new AccessLimitException("访问太频繁啦~");
        }
    }
    public long getRemainingTime(String key) {
        Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire == null ? -1 : expire;
    }


}
